--检查第一候选词是否为纯字母
local function envIsAlphaNum(sIn)
   return (string.match(sIn, "[^%w]") == nil)
end
local P = {}

-- 单字唯一候选词自动上屏 符合唯一码上屏的原则
function P.func(key, env)
   local engine              = env.engine
   local context             = engine.context
   local input_code          = context.input
   local preedit_code_length = utf8.len(input_code)

   if (preedit_code_length > 1 and preedit_code_length < 6) then
      local composition = env.engine.context.composition
      if (not composition:empty()) then
         local segment = composition:back()
         if segment == nil then return end
         -- 获取 Menu 对象
         local menu = segment.menu
         -- 获得（已加载）候选词数量
         local loaded_candidate_count = menu:candidate_count()
         if (loaded_candidate_count == 1) then
            local candidate_text = context:get_selected_candidate().text

            if (preedit_code_length ~= nil) then
               if (not envIsAlphaNum(candidate_text) and preedit_code_length==5) then
                  context:clear_previous_segment()
                  engine:commit_text(candidate_text)
                  return 2 -- kAccepted
               end
            end
         end
      end
   end
   return 2 -- kNoop
end

unique_code_commit = P
